<template>
  <div class="business-detail">
    <!-- 顶部导航 -->
    <div class="header-search">
      <div @click="onClickLeft" class="icon"><van-icon class="back" name="arrow-left" /></div>
      <van-search
        v-model="params.keyword"
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 商家信息 -->
    <div class="card-info">
      <div class="card-header">
        <img class="avatar" :src="merchantInfo.headUrl || avatar" alt="avatar" />
        <div class="info">
          <p class="p1" @click="showBottom = true">
            <span class="name van-ellipsis">{{ merchantInfo.userCompanyAuthDTO.companyName }}</span
            ><span class="icon" v-if="merchantInfo.companyAuthType == 1">企</span
            ><van-icon name="arrow" />
          </p>
          <p class="p2">
            <span>{{ merchantInfo.userCompanyAuthDTO.companyContactMobile }}</span
            ><span>粉丝数</span><span class="count">{{ merchantInfo.storeBeFavoriteNum }}</span>
          </p>
          <p class="p3">
            <van-icon name="shop-o" /><span>{{ merchantInfo.year }}年苗店</span>
          </p>
        </div>
        <van-button color="#32BC05" size="mini" class="focus">{{
          merchantInfo.favoriteStoreState ? '取消关注' : '关 注'
        }}</van-button>
      </div>
      <div class="card-desc">
        <van-icon name="notes" />
        <p class="van-ellipsis">{{ merchantInfo.userCompanyAuthDTO.companyDesc }}</p>
      </div>
    </div>

    <div class="goods-info">
      <div class="tab">
        <span @click="showBottom = true">苗店介绍</span><span class="active">全部苗木</span>
      </div>

      <van-dropdown-menu>
        <van-dropdown-item v-model="mp" :options="options" @change="selectMp"></van-dropdown-item>
      </van-dropdown-menu>

      <div class="list">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="true"
        >
          <div class="item" v-for="item in list" :key="item.id" @click="handleDetail(item)">
            <img :src="item.imgUrl" />
            <p class="name">
              <span class="goods-name van-ellipsis">{{ item.title }}</span
              ><van-tag color="#C9E1C2" round type="primary">{{ item.categoryName }}</van-tag>
            </p>
            <p class="attr-item" v-for="(attr, index) in item.attributeDocuments" :key="index">
              {{ attr.attributeName }}:{{ attr.minValue }}-{{ attr.maxValue }}{{ attr.unit }}
            </p>
            <p class="amount">
              <span>库存 {{ item.pushNum }}</span>
              <span class="am" v-if="item.priceType == 1">面议</span>
              <span class="am" v-if="item.priceType == 2"
                >￥{{ item.priceMin }}-{{ item.priceMax }}/棵</span
              >
            </p>
          </div>
        </van-list>
      </div>
    </div>

    <van-popup
      v-model:show="showBottom"
      position="bottom"
      :style="{ height: '80%' }"
      round
      closeable
    >
      <template #default>
        <div class="navbar">
          <img :src="merchantInfo.headUrl || avatar" />{{
            merchantInfo.userCompanyAuthDTO.companyName
          }}
        </div>
        <div class="desc-item van-hairline--bottom">
          <div class="d1"><van-icon name="notes-o" />最新公告</div>
          <div class="d2">{{ merchantInfo.userCompanyAuthDTO.businessCategory }}</div>
        </div>
        <div class="desc-item van-hairline--bottom">
          <div class="d1"><van-icon name="newspaper-o" />企业介绍</div>
          <div class="d2">{{ merchantInfo.userCompanyAuthDTO.companyDesc }}</div>
        </div>
        <div class="desc-item van-hairline--bottom">
          <div class="d1"><van-icon name="location-o" />企业地址</div>
          <div class="d2">
            {{
              `${merchantInfo.userCompanyAuthDTO.province}${merchantInfo.userCompanyAuthDTO.city}`
            }}
          </div>
        </div>
        <div class="desc-item van-hairline--bottom">
          <div class="d1"><van-icon name="diamond-o" />已获认证</div>
          <div class="d2">
            <p v-if="merchantInfo.companyAuthType == 1"><img :src="safe" /><span>企业认证</span></p>
            <p>
              <img :src="shop" /><span>{{ merchantInfo.year }}年苗店</span>
            </p>
          </div>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script setup>
import bridge from '@/utils/bridge'
import { getMerchantInfo, favorite, unFavorite, companyDetail, byUserId, userInfo } from '@/api'
import avatar from '@/assets/avatar.png'
import safe from '@/assets/safe.png'
import shop from '@/assets/shop.png'
const router = useRouter()
// 搜索条件
const params = ref({
  pageSize: 10,
  pageNum: 1,
  keyword: ''
})
const loading = ref(false)
const finished = ref(false)
const userId = ref('')
const showBottom = ref(false)
const mp = ref(0)
const options = ref([])
const list = ref([])
// 苗商信息
const merchantInfo = ref({
  userCompanyAuthDTO: {}
})

const onClickLeft = () => {
  bridge.closeWebView()
}

const onSearch = () => {}

// 获取登录用户信息
const getUserInfo = async () => {
  let { code, data } = await userInfo()
  if (code === 200) {
    userId.value = data.userId
  }
}

// 苗商信息
const getMxInfo = async () => {
  let { code, data } = await getMerchantInfo({
    userId: userId.value,
    source: 1
  })
  if (code === 200) {
    merchantInfo.value = data
    merchantInfo.value.year = calculateAge(new Date(data.createTime))
  }
}

// 获取苗圃信息
const getListByUserId = async () => {
  let { code, data } = await byUserId({
    userId: userId.value
  })
  if (code === 200) {
    options.value = []
    data.map((item) => {
      options.value.push({
        text: `${item.nurseryName}(${item.total})`,
        value: item.userNurseryId
      })
    })
    options.value.unshift({
      text: `全部(${options.value.length})`,
      value: 0
    })
  }
}

// 切换苗圃
const selectMp = (value) => {
  console.log(value)
  list.value = []
  if (value === 0) {
    value = null
  }
  getCompanyDetail({
    userId: userId.value,
    userNurseryId: value,
    ...params.value
  })
}

const getCompanyDetail = async (params) => {
  loading.value = true
  try {
    let res = await companyDetail(params)
    if (res.code === 200) {
      if (res.rows && res.row.length > 0) {
        res.rows.map((item) => {
          item.imgUrl = item.ossUrls.split(',')[0]
        })
        list.value.push(...res.rows)
        if (list.value.length >= res.total) {
          finished.value = true
        }
      } else {
        finished.value = true
      }
    }
  } finally {
    loading.value = false
  }
}

const handleDetail = (item) => {
  console.log(item.id)
  router.push({
    path: '/seedingsDetail',
    query: {
      pushProductId: item.id
    }
  })
}

const onLoad = () => {
  if (userId.value) {
    params.value.pageNum++
    getCompanyDetail({
      userId: userId.value,
      userNurseryId: null,
      ...params.value
    })
  }
}

const calculateAge = (beginTime) => {
  let ageDifMs = Date.now() - beginTime
  let ageDate = new Date(ageDifMs)
  return Math.abs(ageDate.getUTCFullYear() - 1970) + 1
}

onMounted(async () => {
  // 隐藏原生导航
  bridge.setNavigationBarVisible({
    value: '0'
  })
  await getUserInfo()
  getMxInfo()
  getListByUserId()
  getCompanyDetail({
    userId: userId.value,
    userNurseryId: null,
    ...params.value
  })
})
</script>

<style lang="scss" scoped>
.business-detail {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  background-color: #fff;
  padding-top: constant(safe-area-inset-top);
  /* 标准 */
  padding-top: env(safe-area-inset-top);
  /* iOS 11.0+ */

  .header-search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;

    .icon {
      width: 20px;
      height: 30px;
      text-align: left;
      line-height: 30px;

      .van-icon {
        font-size: 17px;
      }
    }

    :deep(.van-search) {
      flex: 1;

      .van-cell {
        font-size: 13px;
      }

      .van-search__action {
        padding: 0 0 0 10px;
        font-size: 13px;
      }
    }
  }

  .card-info {
    margin: 12px;
    padding: 16px 10px;
    border-radius: 10px;
    box-shadow: 0px 0 8px 0px rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;

      .avatar {
        display: block;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 10px;
        object-fit: cover;
      }

      .info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 10px;

        .p1 {
          display: flex;
          align-items: center;
          gap: 4px;

          .name {
            font-size: 14px;
            color: #222;
            width: 180px;
          }

          .icon {
            font-size: 10px;
            border: 1px solid #c8933b;
            color: #c8933b;
            border-radius: 2px;
          }
        }

        .p2 {
          display: flex;
          align-items: center;
          gap: 6px;
          flex: 1;
          font-size: 11px;
          color: #666666;

          .count {
            color: #32bc05;
          }
        }

        .p3 {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #32bc05;
          font-size: 11px;
        }
      }
    }

    .card-desc {
      margin-top: 12px;
      padding: 9px 4px;
      display: flex;
      align-items: center;
      gap: 6px;
      color: #32bc05;
      font-size: 13px;
      background: rgba(50, 188, 5, 0.1);

      p {
        width: 90%;
      }
    }
  }

  .goods-info {
    padding: 16px 10px;

    .tab {
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      font-size: 14px;
      color: #9e9e9e;

      .active {
        color: #32bc05;
      }
    }

    :deep(.van-dropdown-menu__bar) {
      box-shadow: none;
    }

    :deep(.van-dropdown-menu__item) {
      flex: none;
      color: #222222;
      font-size: 14px;
    }

    .van-list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 4%;

      .item {
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        width: 48%;
        gap: 6px;

        img {
          display: block;
          width: 100%;
          height: 128px;
          object-fit: cover;
          border-radius: 8px;
        }

        .name {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 15px;
          color: #222;
          line-height: 21px;

          .goods-name {
            max-width: 70%;
          }
        }

        .attr-item {
          font-size: 12px;
          color: #222222;
          line-height: 17px;
        }

        .amount {
          font-size: 12px;
          color: #666666;
          line-height: 15px;

          .am {
            margin-left: 6px;
            color: #32bc05;
          }
        }
      }
    }

    :deep(.van-list__finished-text) {
      width: 100%;
    }
  }

  .navbar {
    margin: 24px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #222222;
    line-height: 14px;
    gap: 6px;

    img {
      display: block;
      object-fit: cover;
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }
  }

  :deep(.van-popup__close-icon--top-right) {
    font-size: 14px;
    color: #222;
  }

  .desc-item {
    padding: 12px;

    .d1 {
      display: flex;
      align-items: center;
      color: #9d9898;
      font-size: 13px;
      gap: 5px;
    }

    .d2 {
      margin-top: 8px;
      font-size: 13px;
      color: #222222;
      line-height: 18px;
      display: flex;
      gap: 20px;

      p {
        display: flex;
        align-items: center;
        gap: 5px;

        img {
          width: 22px;
          height: 22px;
          display: block;
          object-fit: cover;
        }
      }
    }
  }
}
</style>
